package routes

import (
	"encoding/json"
	"fmt"
	"gitee.com/zxk7516/laral/models"
	"gitee.com/zxk7516/laral/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"golang.org/x/crypto/bcrypt"
	"strings"
)

type LoginController struct {
	beego.Controller
}

func (this *LoginController) Get() {

	this.TplName = "auth/login.html"
}

func (this *LoginController) Post() {
	contentType := this.Ctx.Request.Header.Get("Content-Type")
	form := models.UserLogin{}
	if strings.ToLower(contentType) == "application/json" {
		err := json.Unmarshal(this.Ctx.Input.RequestBody, &form)
		if err != nil {
			fmt.Println(err.Error(), this.Ctx.Input.RequestBody)
		}
	} else {
		form.Email = this.GetString("email")
		form.Password = this.GetString("password")
	}

	o := orm.NewOrm()
	user := models.User{}
	qs := o.QueryTable(user)
	qs.Filter("email", form.Email).One(&user)
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(form.Password))
	if err == nil {
		user.Password = ""
		this.Data["json"] = utils.Json{"登录成功", user}
		this.ServeJSON()
	} else {
		this.Abort("401")
		//this.Data["json"] = utils.Json{"登录成功", nil}
	}

}
